package com.kye.express.business.jd_reservation.edit;

import android.app.Activity;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.util.TypedValue;
import android.view.View;

import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.express.R;
import com.kye.express.business.base.BaseAppCompatActivity;
import com.kye.express.databinding.ActivityJdWaybillListBinding;
import com.kye.express.utils.ToolbarManager;
import com.kye.express.view.ToastManager;
import com.kye.express.view.reclyerview.OnItemClickListener;
import com.kye.lib.view.statuslayout.StatusLayout;
import com.kye.model.base.PageInfo;
import com.kye.model.bean.jd_reservation.JDWaybillsBean;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.yqritc.recyclerviewflexibledivider.HorizontalDividerItemDecoration;

import java.util.List;

import io.reactivex.functions.Consumer;
import me.drakeet.multitype.MultiTypeAdapter;

public class JdWaybillListActivity extends BaseAppCompatActivity implements JdWaybillListContract.JdWaybillListView {

    public static final String KEY_JDWAYBILL = "KEY_JDWAYBILL";

    private ActivityJdWaybillListBinding mBinding;
    private MultiTypeAdapter mAdapter;
    private JDWaybillViewBinder mBinder;
    private PageInfo mPageInfo;
    private Controller mController;
    private JdWaybillListContract.JdWaybillListPresenter mPresenter;

    public static void startActivityForResult(Activity activity, int requestCode) {
        activity.startActivityForResult(new Intent(activity, JdWaybillListActivity.class), requestCode);
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_jd_waybill_list);

        initView();
        initEvent();
        initData();
    }

    private void initView() {
        mBinding.recyclerViewContent.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerViewContent.addItemDecoration(new HorizontalDividerItemDecoration.Builder(this)
                .margin((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 15, getResources().getDisplayMetrics()), 0)
                .color(R.color.divider)
                .size((int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 0.1F, getResources().getDisplayMetrics()))
                .build());
        mAdapter = new MultiTypeAdapter();
        mAdapter.setHasStableIds(true);
        mBinder = new JDWaybillViewBinder();
        mAdapter.register(JDWaybillsBean.JDWaybill.class, mBinder);
        mBinding.recyclerViewContent.setAdapter(mAdapter);
    }

    private void initEvent() {
        ToolbarManager.setToolbar(this, mBinding.toolbar);

        RxView.clicks(mBinding.linearLayoutErrorNet.btErrorNetRetry)
                .compose(new DebounceObservableTransformer<>())
                .compose(bindToLifecycle())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.statusLayout.showLoadingView();
                    }
                });

        RxView.clicks(mBinding.linearLayoutErrorServer.btErrorServerRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.statusLayout.showLoadingView();
                    }
                });
        RxView.clicks(mBinding.linearLayoutEmpty.btEmptyRetry)
                .compose(new DebounceObservableTransformer<>())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mBinding.statusLayout.showLoadingView();
                    }
                });

        mBinding.statusLayout.setOnLoadingListener(new StatusLayout.OnLoadingListener() {
            @Override
            public void onLoading() {
                mPresenter.load(mPageInfo.resetPage(), mPageInfo.getPageSize(), false);
            }
        });

        mBinding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPresenter.load(mPageInfo.increasePage(), mPageInfo.getPageSize(), true);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.load(mPageInfo.resetPage(), mPageInfo.getPageSize(), true);
            }
        });

        mController = new Controller();
        mController.setListener(new Controller.Listener() {
            @Override
            public void onRefresh() {
                mBinding.refreshLayout.autoRefresh();
            }

            @Override
            public void onLoading() {
                mBinding.statusLayout.showLoadingView();
            }

            @Override
            public void onLoadMore() {
                mBinding.refreshLayout.autoLoadmore();
            }

            @Override
            public void onEnableLoadMore(boolean b) {
                mBinding.refreshLayout.setEnableLoadmore(b);
            }

            @Override
            public void onShowEmptyView() {
                mBinding.statusLayout.showEmptyView();
            }

            @Override
            public void onSetItems(List items, List newItems) {
                mAdapter.setItems(items);
                mAdapter.notifyDataSetChanged();
            }

            @Override
            public void onShowErrorServerView() {
                mBinding.statusLayout.showErrorServerView();
            }

            @Override
            public void onApiError(String msg) {
                ToastManager.show(getApplicationContext(), msg);
            }

            @Override
            public void onShowErrorNetworkView() {
                mBinding.statusLayout.showErrorNetworkView();
            }

            @Override
            public void onError() {
                ToastManager.show(getApplicationContext(), R.string.common_net_error);
            }

            @Override
            public void onFinishRefresh() {
                mBinding.refreshLayout.finishRefresh();
            }

            @Override
            public void onShowContentView() {
                mBinding.statusLayout.showContentView();
            }

            @Override
            public void onFinishLoadMore() {
                mBinding.refreshLayout.finishLoadmore();
            }
        });

        mBinder.setOnItemClickListener(new OnItemClickListener<JDWaybillsBean.JDWaybill>() {
            @Override
            public void onClickItem(JDWaybillsBean.JDWaybill item, View view) {
                setResult(RESULT_OK, new Intent().putExtra(KEY_JDWAYBILL, item));
                finish();
            }
        });
    }

    private void initData() {
        mPresenter = new JdWaybillListContract.JdWaybillListPresenter();
        mPresenter.bind(this);

        mPageInfo = PageInfo.newInstance();

        mBinding.statusLayout.showLoadingView();
    }

    @Override
    public void onLoading(int pageIndex, boolean hasData) {
        mController.onLoading(pageIndex, hasData);
    }

    @Override
    public void onLoadData(JDWaybillsBean jdWaybillsBean, int pageIndex, boolean hasData) {
        mController.onLoadData(jdWaybillsBean.getDatas(), pageIndex, hasData, mPageInfo.getPageSize(), mAdapter.getItems());
    }

    @Override
    public void onApiError(int pageIndex, boolean hasData, String msg) {
        mController.onApiError(pageIndex, hasData, msg);
    }

    @Override
    public void onError(int pageIndex, boolean hasData) {
        mController.onError(pageIndex, hasData);
    }

    @Override
    public void onLoaded(int pageIndex, boolean hasData) {
        mController.onLoaded(pageIndex, hasData);
    }
}
